package com.kilman.logger.log;

import java.io.IOException;

import com.kilman.logger.ssh.ContinuousSSHExecution;
import com.kilman.logger.ssh.SSHUtils;

public class RawActiveLog extends ContinuousSSHExecution {

    private static final String TAIL_COMMMAND_PREFIX = "tail -n+0 -f ";
    private static final String KILL_TAIL_COMMAND_PREFIX = "ps x | grep \"";
    private static final String KILL_TAIL_COMMAND_SUFFIX = "\" | grep -v grep | awk '{ print $1 }' | xargs kill -9";
    private static final String KILL_ALL_TAIL_COMMAND_PREFIX = "killall -9 -u ";
    private static final String KILL_ALL_TAIL_COMMAND_SUFFIX = "tail";
    
    public RawActiveLog(String path, String host,String username, String password) {
        super(TAIL_COMMMAND_PREFIX + path, 0, host, username, password);
    }

    @Override
    public void endExecution() {
        super.endExecution();
        String host = getHost();
        String username = getUserInfo().getName();
        String password = getUserInfo().getPassword();
        String command = KILL_TAIL_COMMAND_PREFIX + getCommand() + KILL_TAIL_COMMAND_SUFFIX;
        long timeout = 1000;
        
        try {
            SSHUtils.runCommand(command, timeout, host, username, password);
        } catch (IOException e) { /* caused by file open, we don't care */ }
    }
    
    
    public static void killAllRawActiveLogsByUsername(String host,String username, String password) {
        try {
            String command = KILL_ALL_TAIL_COMMAND_PREFIX + username + " " + KILL_ALL_TAIL_COMMAND_SUFFIX;
            SSHUtils.runCommand(command, 1000, host, username, password);
        } catch (IOException e) { /* caused by file open, we don't care */ }
    }
    
}
